import React, { useState, useRef, useCallback } from 'react';
import { Common } from 'UtilsCommon';
import Components from 'Components';
import Base from './base';

const iso = Common.isIos();

const validateImage = (file, pageAxis) => {
    if (!/image/.test(file.type)) { pageAxis.alert("请选择图片"); return; }

    const reg = /\.(jpg|jpeg|png)$/i;
    if (!reg.test(file.name)) { pageAxis.alert("请选择jpg、jpeg、png格式图片"); return; }

    // 大于 10MB
    if (file && file.size > 1024 * 1024 * 10) { pageAxis.alert('请使用小于10MB的图片'); return; }
    return true;
};

const getImage = (file, property) => {
    const { width, height, type, quality, maxWidth, maxHeight, maxSize } = property;

    if (maxSize && file.size < maxSize * 1024) return Promise.resolve(file);

    return Common.compressImage(file, width, height, type || 'image/png', quality || 1, maxWidth, maxHeight).then(res => {
        return Promise.resolve(Common.dataURLtoFile(res, file.name));
    });
};

const uploadImage = (e, pageAxis, property, value, setValue) => {
    if (e.target.files.length === 0) return;

    if (e.target.files.length + value.length > property.imagesCount) {
        pageAxis.alert(property.overImagesCountTip);
        return;
    }

    let blSuccess = true;

    const fileList = [];

    for (let i = 0; i < e.target.files.length; i++) {
        const file = e.target.files[i];
        if (!validateImage(file, pageAxis)) {
            blSuccess = false;
            break;
        }

        fileList.push(getImage(file, property));
    }

    if (!blSuccess) return;

    Promise.all(fileList).then(res => {
        const list = value.map(m => m);
        res.forEach(file => {
            list.push({
                src: URL.createObjectURL(file),
                file
            });
        });
        setValue(list);
    });
};

const renderItem = (value, index, imageProperty, property, pageId, PropertyItem) => {
    const p = Common.clone(imageProperty);
    p.currentIndex = index;
    p.id = Common.createGuid();
    p.properties && p.properties.forEach(p1 => { if (p1.isEdit) p1.value = value.src; p1.currentIndex = index; });
    if (p.isEdit) p.value = value.src;

    return <PropertyItem property={p} view={property} pageId={pageId} key={p.id} />;
};

export default (props) => {
    const { PropertyItem } = Components;
    const { property, pageAxis, pageId } = Base.getProps(props);
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);
    const [value, setValue] = useState([]);

    const inputFile = useRef(null);

    const onChange = useCallback((e) => {
        uploadImage(e, pageAxis, property, value, setValue);
    }, [pageAxis, property, value, setValue]);

    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };
    property.setValue = (v) => setValue(v || []);
    property.getValue = () => value;

    pageAxis.uploadImageAction = () => {
        if (value.length === 6) {
            pageAxis.alert(property.overImagesCountTip);
            return;
        }
        inputFile.current.click();
    };
    pageAxis.removeImageAction = (props) => {
        const index = props.property.currentIndex;
        setValue(value.filter((t, i) => i !== index));
    };

    if (!isVisible) return null;

    const { className, style, imagesCount, imagesStyle } = property;

    const buttonProperty = property.properties[0];
    const imageProperty = property.properties[1];
    const button0Property = property.properties.length === 3 ? property.properties[2] : null;
    buttonProperty.eventActionName = 'uploadImageAction';
    button0Property.eventActionName = 'uploadImageAction';

    const isHasImageButton = button0Property ? value.length > 0 : value.length < imagesCount;

    return (<div className={className} style={Base.setStyle(style)}>
        {value.length > 0 && <div style={Base.setStyle(imagesStyle)}>
            {value.map((m, i) => renderItem(m, i, imageProperty, property, pageId, PropertyItem))}
        </div>}
        {isHasImageButton && <PropertyItem property={buttonProperty} view={property} pageId={pageId} />}
        {button0Property && value.length === 0 && <PropertyItem property={button0Property} view={property} pageId={pageId} />}
        <input type='file' accept='image/*' value='' onChange={onChange} multiple={iso ? 'multiple' : ''} ref={inputFile} style={{ display: 'none' }} />
    </div>);
};